package com.atguigu.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.common.model.hosp.Department;
import com.atguigu.yygh.common.vo.hosp.DepartmentQueryVo;
import com.atguigu.yygh.common.vo.hosp.DepartmentVo;
import com.atguigu.yygh.hosp.repository.DepartmentRepository;
import com.atguigu.yygh.hosp.service.DepartmentService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author LY
 */
@Service
public class DepartmentServiceImpl implements DepartmentService {

    @Autowired
    private DepartmentRepository departmentRepository;

    /**
     * 上传科室接口
     * @param paramMap
     */
    @Override
    public void save(Map<String, Object> paramMap) {
        //1. 将Map进行转换
        Department department = JSONObject.parseObject(JSONObject.toJSONString(paramMap), Department.class);

        String hoscode = department.getHoscode();
        String depcode = department.getDepcode();

        //2. 通过医院编号和科室编号查询是否存在科室
       Department targetDepartment = departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode,depcode);

       //3. 判断如果Department不为空,执行修改,为空,执行保存
        if (null!=targetDepartment){
            targetDepartment.setUpdateTime(new Date());
            targetDepartment.setIsDeleted(0);
            //执行更新
            departmentRepository.save(targetDepartment);
        }else {
            department.setCreateTime(new Date());
            department.setUpdateTime(new Date());
            department.setIsDeleted(0);
            //4. 执行保存
            departmentRepository.save(department);
        }

    }

    /**
     * 查询科室接口
     * @param page 当前页
     * @param limit 每页显示数量
     * @param departmentQueryVo 条件对象
     * @return
     */
    @Override
    public Page<Department> findPage(Integer page, Integer limit, DepartmentQueryVo departmentQueryVo) {
        //1. 排序条件
        Sort sort = Sort.by(Sort.Direction.DESC,"createTime");
        //2.分页接口
        Pageable pageable = PageRequest.of(page-1,limit,sort);
        //3.复制对象
        Department department = new Department();
        BeanUtils.copyProperties(departmentQueryVo,department);
        department.setIsDeleted(0);

        /*
         * 4. 创建匹配器，即如何使用查询条件
         */
        //构建对象
        ExampleMatcher matcher  = ExampleMatcher.matching()
                                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                                //改变默认字符串匹配方式：模糊查询
                                .withIgnoreCase(true);

        //5.创建条件实例
        Example<Department> example = Example.of(department,matcher);

        //6.返回多个对象并分页
        Page<Department> departments = departmentRepository.findAll(example, pageable);
        return departments;
    }

    /**
     * 删除科室接口
     *
     * @param hoscode 医院编号
     * @param depcode 科室编号
     */
    @Override
    public void remove(String hoscode, String depcode) {
        //1.获取Department对象
        Department department = departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
        //2.判断如果不为空,就执行删除
        if (null!=department){
            //根据id删除
            departmentRepository.deleteById(department.getId());
        }

    }

    @Override
    public List<DepartmentVo> findDepartTree(String hoscode) {

        //创建list集合，用于最终数据的封装
        List<DepartmentVo> result = new ArrayList<>();

        //根据医院编号，查询所有科室信息
        Department departmentQuery = new Department();
        departmentQuery.setHoscode(hoscode);
        Example<Department> example = Example.of(departmentQuery);
        //所有科室列表信息
        List<Department> departmentList = departmentRepository.findAll(example);

        //根据大科室编号  bigCode分组,获取每个大科室里面的下级子科室
        Map<String, List<Department>> departmentMap
                = departmentList.stream().collect(Collectors.groupingBy(Department::getBigcode));

        //遍历departmentMap集合
        for (Map.Entry<String,List<Department>> entry :departmentMap.entrySet()){

            //大科室编号
            String bigCode = entry.getKey();
            //大科室编号对应的全部数据
            List<Department> departments = entry.getValue();

            //封装大科室
            DepartmentVo departmentVo = new DepartmentVo();
            departmentVo.setDepcode(bigCode);
            departmentVo.setDepname(departments.get(0).getDepname());
            //封装小科室
            List<DepartmentVo> children = new ArrayList<>();
            for (Department department:departments){
                DepartmentVo departmentVoChildren = new DepartmentVo();
                departmentVoChildren.setDepcode(department.getDepcode());
                departmentVoChildren.setDepname(department.getDepname());
                //封装到children集合中去
                children.add(departmentVoChildren);
            }
            //封装到大科室中
            departmentVo.setChildren(children);
            //放到最终result集合中去
            result.add(departmentVo);
        }
        return result;
    }

    @Override
    public String getDepName(String hoscode, String depcode) {
       Department department = departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
        if (null!=department){
            return department.getDepname();
        }
        return null;
    }

    @Override
    public Department getDepartment(String hoscode, String depcode) {

        return departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
    }
}
